﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using MQ.Core.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MQ.Core.Admin.Filters
{
    /// <summary>
    /// 登录过滤器
    /// 默认：需要登录 and  返回json  and web api方式请求
    /// </summary>
    public class LoginFilter:ActionFilterAttribute
    {
        private readonly NLog.Logger logger= NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        /// <summary>
        /// 是否需要登录，默认为true
        /// </summary>
        public bool isNeedLogin { set; get; }
        /// <summary>
        /// 响应类型：view   string   json  默认为json
        /// </summary>
        public ResponseType responseType { set; get; }
        /// <summary>
        /// 请求方式：web or api  默认为api
        /// </summary>
        public RequestType requestType { set; get; }

        public LoginFilter(bool isNeedLogin = true,RequestType requestType=RequestType.Api,ResponseType responseType=ResponseType.Json)
        {
            this.isNeedLogin = isNeedLogin;
            this.responseType = responseType;
            this.requestType = requestType;
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (isNeedLogin&&requestType == RequestType.Api)
            {
                //web api请求得首先验证token
                //if (!context.HttpContext.Request.Headers.Keys.Contains("access_token"))
                //{
                //    context.Result = new JsonResult(ResultMsg.Fail(401, "非法请求。"));
                //    logger.Error("非法请求");
                //    return;
                //}
            }
            if (isNeedLogin)
            {
                if (context.HttpContext.Request.Cookies.Keys.Contains("LoginUser"))
                {
                    logger.Error("您还未登录，请先登录。");
                    if (responseType == ResponseType.Json)
                    {
                        context.Result = new JsonResult(ResultMsg.Fail(0, "您还未登录，请先登录。"));
                    }
                    else
                    {
                        context.Result = new RedirectResult("/Manager/Login");
                    }
                }

            }
            base.OnActionExecuting(context);
        }
    }
}
